package com.yc.myFilterFactory;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

@Component
public class MobileAccessGatewayFilterFactory
        extends AbstractGatewayFilterFactory<MobileAccessGatewayFilterFactory.Config> {

    // 移动端User-Agent匹配正则
    private static final Pattern MOBILE_PATTERN = Pattern.compile(
            ".*(android|iphone|ipad|ipod|blackberry|windows phone|mobile).*",
            Pattern.CASE_INSENSITIVE
    );

    public MobileAccessGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("enabled");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            if (!config.isEnabled()) {
                return chain.filter(exchange);
            }

            // 获取User-Agent
            String userAgent = exchange.getRequest().getHeaders().getFirst("User-Agent");

            // 判断是否为移动端
            if (StringUtils.hasText(userAgent) && isMobileUserAgent(userAgent)) {
                return chain.filter(exchange);
            }

            // 非移动端访问，返回403
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        };
    }

    // 判断是否为移动设备User-Agent
    private boolean isMobileUserAgent(String userAgent) {
        return MOBILE_PATTERN.matcher(userAgent).matches();
    }

    public static class Config {
        private boolean enabled = true;

        public boolean isEnabled() {
            return enabled;
        }

        public Config setEnabled(boolean enabled) {
            this.enabled = enabled;
            return this;
        }
    }
}